//
//  ClientManager.m
//  Soccer
//
//  Created by Hyun-Woong Kim on 09. 05. 06.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ClientManager.h"
#import "Lobby.h"
#import "GameScene.h"
#import "MiniMap.h"

@implementation ClientManager

@synthesize match;
@synthesize inputProcessor;

//
// singleton stuff
//
static ClientManager *_sharedManager = nil;

+ (ClientManager *)sharedManager
{
	@synchronized([ClientManager class])
	{
		if (!_sharedManager)
			[[self alloc] init];
		
		return _sharedManager;
	}
	// to avoid compiler warning
	return nil;
}

+ (id)alloc
{
	@synchronized([ClientManager class])
	{
		NSAssert(_sharedManager == nil, @"Attempted to allocate a second instance of a singleton.");
		_sharedManager = [super alloc];
		return _sharedManager;
	}
	// to avoid compiler warning
	return nil;
}

- (id)init
{	
	if (self = [super init])
	{
		checksPerFrame = 1;
		match = [[Match alloc] init];
		inputProcessor = [[InputProcessor alloc] init];
	}
	
	return self;
}

- (void)dealloc
{
	[match release];
	[inputProcessor release];
	[super dealloc];
}

- (void)reset
{
	[match release];
	[inputProcessor release];
	
	match = [[Match alloc] init];
	inputProcessor = [[InputProcessor alloc] init];
}


// Start Game after network setting
- (void)startGameWithLayer:(Layer<MatchDelegate> *)layer;
{
	// Match와 GameLayer 연결
	match.delegate = layer;
	
	// 경기장
	Stadium *stadium = [[Stadium alloc] initWithSize:CGSizeMake(960, 640) groundBounds:CGRectMake(35, 35, 890, 570)
										goalPostSize:CGSizeMake(1, 190)];
	[match setStadium:stadium];
	[stadium release];
	
	// 미니맵
	MiniMap *miniMap = [[MiniMap alloc] initWithSize:CGSizeMake(96,64) position:CGPointMake(430,285)];
	[match setMiniMap:miniMap];
	[miniMap release];
}

// 네트워크에서 받은 정보를 이용하여 플레이어 생성
- (void) InsertPlayer:(NSString *)name index:(int)index team:(int)team isMine:(Boolean)isMine
{
	float pos;
	double dir;
	
	// A팀인 경우
	if(team == 0)
	{
		pos = 0.0f;
		dir = 0;
	}
	// B팀인 경우
	else
	{
		pos = 140.0f;
		dir = kPi;
	}	
		
	Player *thisPlayer = [[Player alloc] initWithPosition:CGPointMake(450 + pos, 320) team:team dirRad:dir];
	
	// 추가하는 플레이어를 내가 조종하는 경우 
	if(isMine == YES)
	{
		thisPlayer.isPlayable = YES;
		inputProcessor.player = thisPlayer;
		match.myself = thisPlayer;
	}
	
	[match addPlayer:thisPlayer];
	[thisPlayer release];
}

// 네트워크에서 받은 정보를 이용하여 골키퍼 생성
- (void) InsertGoalKeeper:(int)team
{	
	GoalKeeper *thisKeeper = [[GoalKeeper alloc] initWithPosition:CGPointZero team:team dirRad:0.];
	[match addPlayer:thisKeeper];
	[thisKeeper release];
}

- (void) InsertBall
{
	Ball *ball = [[Ball alloc] initWithPosition:CGPointZero];
	Player *tempPlayer = [match.players objectAtIndex:0];
	ball.owner = tempPlayer;
	inputProcessor.ball = ball;
	[match setBall:ball];
	[ball release];
}
 


@end